module ActsAsDynamic
  module ActsAsAuthenticated
  
    module ClassMethods
      # Opciones soportadas:
      #   :login_field   Nombre del campo en el que se buscará el nombre de usuario.
      #                  Por defecto ese el email.
      def acts_as_authenticated(options = {})
        include ActsAsDynamic::ActsAsAuthenticated::InstanceMethods
        @login_field = options[:login_field] || :email
      end
  
    end
    
    module InstanceMethods

      def self.included(base) # :nodoc:
        base.extend AuthenticationClassMethods
      end
      
      module AuthenticationClassMethods
        def authenticate(login, password)
          user = find(:first, :conditions => {@login_field => login})
          if !user || Digest::MD5.hexdigest(password.to_s + user.password_salt.to_s) != user.password_hash
            user = nil
          end
          user
        end
      end

      def password=(pass)
        #Tomado de la receta 31 de Rails Recipes
        salt = [Array.new(6){rand(256).chr}.join].pack("m").chomp
        self.password_salt, self.password_hash = salt, Digest::MD5.hexdigest(pass + salt)
      end
      
      def password
        nil
      end
    end
  
  end
end
  
ActiveRecord::Base.extend ActsAsDynamic::ActsAsAuthenticated::ClassMethods
